import React from 'react'
import { useRef, useState } from "react";
import './discoverImg.less'
import { postList } from '../../../api/index'
import * as uuid from 'uuid'
import { Popup, NavBar } from 'react-vant';
export default function DiscoverImg(props) {
    const video = useRef();
    const img = useRef();
    const [state, showState] = useState(true);
    const [stateimg, showImg] = useState();
    const [limte, showLimte] = useState(10240);
    const [text, showText] = useState();
    const [showPopup, setShowPopup] = useState(false);
    //访问用户媒体设备的兼容方法
    function getUserMedia(constraints, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
            //最新的标准API
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
            //webkit核心浏览器
            navigator.webkitGetUserMedia(constraints, success, error)
        } else if (navigator.mozGetUserMedia) {
            //firfox浏览器
            navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
            //旧版API
            navigator.getUserMedia(constraints, success, error);
        }
    }
    function success(stream) {
        //兼容webkit核心浏览器
        let CompatibleURL = window.URL || window.webkitURL;
        //将视频流设置为video元素的源
        video.current.srcObject = stream;
        video.current.play();
    }
    function error(error) {
      
    }
    if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
        //调用用户媒体设备, 访问摄像头
        getUserMedia({
            video: {
                width: 375,
                height: 667
            }
        }, success, error);
    } else {
        alert('不支持访问用户媒体');
    }
    function convertBase64UrlToBlob(urlData) {
        //去掉url的头，并转换为byte         
        var split = urlData.split(',');
        var bytes = window.atob(split[1]);
        //处理异常,将ascii码小于0的转换为大于0  
        var ab = new ArrayBuffer(bytes.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
        }
        return new Blob([ab], { type: split[0].split(';')[0].split(':')[1] });
    }
    
    return (
        <div className='video'>
            <div className='top'>
                {
                    state ? (
                        <svg className="icon icon-zuojiantou" aria-hidden="true" onClick={() => { props.setvisible() }}><use xlinkHref='#icon-zuojiantou'></use></svg>


                    ) : (
                            <>  
                            <svg className="icon icon-zuojiantou" aria-hidden="true"  onClick={() => {
                                showState(!state)
                            }}
                            ><use xlinkHref='#icon-fanhui' className='wwww'></use></svg>
                            <span onClick={() => { setShowPopup(true) }}>确定</span>
                            </>
                          
                     
                    )
                }

            </div>
            {
                state ? <video id="recording" ref={video} className="hide" > </video> : <img className='img' src={stateimg} alt="" />
            }
            {
                state ? <p className='clickImg' onClick={() => {
                    showState(!state)
                    var canvas = img.current
                    let context = canvas.getContext('2d');
                    // context.drawImage(video.current, 0, 0, window.innerWidth, window.innerHeight)
                    context.drawImage(video.current, 0, 0,375,667)
                    showImg(canvas.toDataURL("image/png"))
     
                }}>
                    <span ></span>
                </p> : ''
            }


            <canvas ref={img}  ></canvas>

            <Popup
                className='video-move'
                visible={showPopup}
                onClose={() => setShowPopup(false)}
                style={{ width: '100%', height: '100%' }}
            >
                <NavBar
                    leftArrow
                    rightText="确定"
                    onClickLeft={() => props.setvisible()}
                    onClickRight={() =>{
                        let f = convertBase64UrlToBlob(stateimg);
                        let files = new window.File([f], { type: f.type })
                        let nums = Math.ceil(files.size / 10240)
                        let name = uuid.v1()
                        let user=JSON.parse(localStorage.getItem('token'))
                        for (let i = 0; i < nums; i++) {
                            let start = i * limte
                            let end = i < (nums - 1) ? ((i + 1) * limte) : files.size
                            let formData = new FormData()
                            formData.set('file', files.slice(start, end))
                            formData.set('num', i)
                            formData.set('max', nums)
                            formData.set('filename', name)
                            formData.set('text', text)
                            formData.set('info_id', user.info_id)
                            formData.set('xing', user.name)
                            postList('/zbf/bar', formData).then(res => {
                                if(Object.getOwnPropertyNames(res.data)!=0){
                                    props.setvisible(res.data)
                                }
                            })
                        }
                    }}
                />
                <textarea type="text" placeholder='你这一刻的想法...' onChange={(e)=>{
                    showText(e.target.value)
                }} />
                <img className='img' src={stateimg} alt="" />
            </Popup>

        </div>
    )
}
